$(function () {

    var $indexPage = $("#indexPage");
    var $getBalance = $("#getBalance");
    var $transferAccounts = $("#transferAccounts");
    var $getTransactionRecord = $("#getTransactionRecord");
    var $editPwd = $("#editPwd");
    getCardNo();

    $("menu li").click(function () {
        $(this).addClass("selected").siblings().removeClass("selected");
    });

    //菜单:首页按钮击事件
    $indexPage.click(function () {
        //生成首页
        $("article").remove();
        var str = `<article class="indexPage">
                        <h1>欢迎使用个人网上银行</h1>
                    </article>`;
        $("menu").after(str);
    });

    //菜单:查询余额按钮点击事件
    $getBalance.click(function () {

        $.ajax({
            url:"/bank?action=getBalance",
            data:{},
            type:"post",
            dataType:"json",
            timeout:6000,
            beforeSend:beforeSend,
            success:callBack,
            error:error
        });

        function beforeSend() {
            $("article").remove();
            var str = `<article class="indexPage">
                            <img src="/static/images/loading.gif" width="200px">
                       </article>`;
            $("menu").after(str);
        }

        function callBack(data){
            //生成余额页面
            //console.log(data);
            $("article").remove();
            var str = `<article class="getBalance">
                            <div class="getBalance-content">
                                <p>您的账户余额是：</p>
                                <span>人民币:</span><span>${data}元</span>
                            </div>
                       </article>`;
            $("menu").after(str);
        }

        function error() {
            alert("请求超时！");
            $("article").remove();
            var str = `<article class="getBalance">
                        <div class="getBalance-content">
                            <p>您的账户余额是：</p>
                            <span>人民币:</span><span>--元</span>
                        </div>
                       </article>`;
            $("menu").after(str);
        }

    });

    //菜单:转账按钮点击事件
    $transferAccounts.click(function () {
        //生成转账页面
        $("article").remove();
        var str = `<article class="transfer">
                    <div class="getBalance-content">
                        <h3>请输入转入帐号和金额后点击“转账”按钮</h3>
                            <p>
                            转入帐号：<input type="text" name="account" maxlength="16" />
                            </p>
                            <p>
                            转入金额：<input type="text" name="money" maxlength="10" />
                            </p>
                            <p>
                            <input type="button" value="转账" id="transferAccount" />
                            </p>
                    </div>
                   </article>`;
        $("menu").after(str);
    });

    //菜单：查询交易记录按钮点击事件
    $getTransactionRecord.click(function () {
        //生成查询交易记录页面
        $("article").remove();
        var str = `<article>
                        <div class="getTransactionRecord">
                            <h3>请选择时间范围后点击“查询”按钮</h3>
                            <p class="form">查询日期范围：<input type="text" class="date-picker" readonly="readonly"><input type="button" class="search" value="查询" style="width: 50px"></p>
                        </div>
                    </article>`;
        $("menu").after(str);

        //绑定时间控件
        laydate.render({
            elem : '.date-picker',
            type : 'datetime',
            range : true
        });
    });

    //ajax获取登录用户的卡号
    function getCardNo() {
        $.ajax({
            url:"/bank/main",
            data:{"action":"getCardNo"},
            dataType:"text",
            type:"post",
            // timeout:5000,
            beforeSend:beforeSend,
            success:callBack,
            error:errorBack
        });

        function callBack(data) {
            console.log(data);
            $("#loginInfo").html(`卡号：${data} <a href="main?action=logOut">退出登录</a>`);
        }

        function errorBack() {
            alert("请求超时");
        }

        function beforeSend() {
        }
    }

    //转账按钮点击事件
    $("nav").on("click","#transferAccount",function () {
        var account = $("[name='account']").val();
        var money = $("[name='money']").val();
        var regAccount = /^\d{16}$/;
        var regMoney = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if(account==""){
            alert("转入帐号不能为空！");
            return false;
        }else if(regAccount.test(account)==false){
            alert("请正确填写要转入的16位帐号！");
            return false;
        }else if(money==""){
            alert("转入金额不能为空！");
            return false;
        }else if(regMoney.test(money)==false){
            alert("请正确填写转账金额！");
            return false;
        }else if(money <= 0){
            alert("请正确填写转账金额！");
            return false;
        }
        transferAccountByAjax(account,money);

        //ajax转账
        function transferAccountByAjax(account,money) {
            $.ajax({
                url : "/bank/main",
                type: "post",
                data: {"action":"transferAccount","account":account,"money":money},
                dataType : "text",
                beforeSend:beforeSend,
                success : callBack,
                error : error
            })
        }

        function beforeSend() {
            $("article").remove();
            var str = `<article class="transfer">
                            <div class="getBalance-content">
                                <img src="/static/images/loading.gif" width="200px">
                            </div>
                       </article>`;
            $("menu").after(str);
        }

        function callBack(data) {
            console.log(data);
            if(data!="success"){
                alert(data);
            }else{
                //生成转账页面
                $("article").remove();
                var str = `<article class="transfer">
                            <div class="getBalance-content">
                                <h3>操作已成功！请继续选择其他服务</h3>
                            </div>
                           </article>`;
                $("menu").after(str);
            }
        }

        function error(data) {
            alert(data+" 转账失败！");

        }

    });

    //查询交易记录菜单项：查询按钮
    $("nav").on("click",".search",function(){
        var currentPage = $("#currentPage").attr("value");
        getRecordAndPage();

    });

    //获取记录和分页数据
    function getRecordAndPage() {
        var timeFrame = $(".form>.date-picker").val();
        var timeArray = timeFrame.split(" - ");
        var start = timeArray[0];
        var end = timeArray[1];
        getRecordByAjax();
        //使用ajax获取交易记录
        function getRecordByAjax() {
            $.ajax({
                url : "main?action=getTransactionRecord",
                data : {start:start,end:end},
                type: "post",
                dataType : "json",
                success : callBack,
                error : error
            });

            function callBack(data){
                $("table").remove();
                console.log(data);
                var table = `<table border="1" align="center" width="600px" style="margin: 0 auto;border-collapse: collapse;border: 1px solid lightgray;">
                        <tr>
                            <th>交易日期</th>
                            <th>支出</th>
                            <th>存入</th>
                            <th>账户余额</th>
                            <th>交易类型</th>
                            <th>备注</th>
                        </tr>
                        <tr>
                            <td colspan="6">
                                <a href="javascript:;" id="first">首页</a>
                                <a href="javascript:;" id="pre">上一页</a>
                                <a href="javascript:;" id="next">下一页</a>
                                <a href="javascript:;" id="last">末页</a>
                                第<span id="currentPage" value="">--</span>页/共<span id="totalPage">--</span>页
                                共<span id="totalCount">--</span>条记录
                            </td>
                        </tr>
                    </table>`;
                $(".getTransactionRecord").after(table);
                var str = "";
                $(data).each(function (index,obj) {
                    str += `<tr>
                            <td>${obj.transaction_date}</td>
                            <td>${obj.expense}</td>
                            <td>${obj.income}</td>
                            <td>${obj.balance}</td>
                            <td>${obj.transaction_type}</td>
                            <td>${obj.remark}</td>
                        </tr>`;
                });
                $("table tr:first").after(str);
                getPage();
            }

            function error(data) {
                console.log(data);
            }
        }

        //使用ajax获取分页信息
        function getPage() {
            $.ajax({
                url : "main?action=getPage",
                data : {start:start,end:end,currentPage:$("#currentPage").attr("value")},
                type: "post",
                dataType : "json",
                success : callBack,
                error : error
            });

            function callBack(data) {
                console.log(data);
                $("#totalCount").text(data.totalCount);
                $("#totalPage").text(data.totalPage);
                $("#currentPage").text(data.currentPage).attr("value",data.currentPage);
            }

            function error(data) {
                console.log(data);
            }
        }
    }

    //下一页按钮点击事件
    $("nav").on("click","#next",function () {
        var currentPage = $("#currentPage").attr("value");
        currentPage++;
        alert(currentPage);
    });

    //首页按钮点击事件
    $("nav").on("click","#first",function () {
        var currentPage = $("#currentPage").attr("value");
        alert(currentPage);
    });
});


